import { Editor, Transforms, Element } from 'slate';
import { EDITOR_ELEMENT_TYPE, PLUGINS_KEYS, Plugin, commandType } from '../types';
import './index.less';
import { isCollapsed, isFouceStart, isMatchKeyDown } from '@/core/utils/is';
import { KEYDOWNS } from '@/core/types';
import { getBlockMatch } from '@/core/utils/get';
import { setBlockNode, setWrapNode } from '@/core/utils/set';

const command: commandType = (editor) => {
  setBlockNode(editor, {
    [PLUGINS_KEYS.QUOTELISTITEM]: true,
  });
  setWrapNode(editor, {
    [PLUGINS_KEYS.QUOTELIST]: true,
  });
};

function Quote(editor: Editor): Plugin {
  return {
    key: PLUGINS_KEYS.QUOTELIST,
    type: EDITOR_ELEMENT_TYPE.BLOCK,
    match: (props) => !!props.element[PLUGINS_KEYS.QUOTELIST],
    command,
    render: (context) => {
      return <blockquote>{context.children}</blockquote>;
    },
    onKeyDown: (event) => {
      if (isMatchKeyDown(event, KEYDOWNS.BACKSPACE, KEYDOWNS.ENTER) && isCollapsed(editor)) {
        const { block, path } = getBlockMatch(editor);
        if (!block[PLUGINS_KEYS.QUOTELIST] && !block[PLUGINS_KEYS.QUOTELISTITEM]) return null;
        if (isFouceStart(editor, path)) {
          event.preventDefault();
          Transforms.unsetNodes(editor, [PLUGINS_KEYS.QUOTELISTITEM]);
          Transforms.unwrapNodes(editor, {
            match: (n) => {
              return !Editor.isEditor(n) && Element.isElement(n) && !!n[PLUGINS_KEYS.QUOTELIST];
            },
            split: true,
          });
        }
      }
    },
  };
}
export default Quote;
